<template>
  <div id="address_management">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="16" :sm="24">
              <!--<a-form-item label="商品分类名称">
                <a-input v-model="queryParam.name" placeholder="请输入商品分类名称"></a-input>
              </a-form-item>-->
            </a-col>
            <a-col :md=" 8 || 24" :sm="24">
              <a-button type="primary" @click="addProvince">新增省</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
        :columns="columns"
        :dataSource="cityData"
        childrenColumnName="regions"
        rowKey="id"
        :rowSelection="rowSelection" >
        <div slot="state" slot-scope="text" >
          <a-tag color="blue">{{ text | statusFilter }}</a-tag>
        </div>
        <div slot="type" slot-scope="text" >
          <a-tag color="blue">{{ text | typeFilter }}</a-tag>
        </div>
        <span slot="action" slot-scope="record">
          <a @click.prevent="showAddressModal(record)">新增</a>
          <a-divider type="vertical"></a-divider>
          <a @click.prevent="showEditModal(record)">编辑</a>
          <a-divider type="vertical"></a-divider>
          <a-popconfirm
            title="确认删除?"
            @confirm="() => delAddress(record.id)">
            <a href="javascript:">删除</a>
          </a-popconfirm>
          <a-divider type="vertical"></a-divider>
          <a @click.prevent="changeShelves(record)">上架</a>
        </span>
      </a-table>
    </a-card>

    <!--新增地址弹窗-->
    <a-modal
      title="新增地址"
      :visible="visible"
      @ok="saveAddress"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      <div>
        <a-form :form="dialogModel">
          <a-form-item
            label="地址"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <a-input
              v-decorator="[
                'name',
                {rules: [{ required: true, message: '请输入地址!!' }]}
              ]"
              placeholder="请输入地址..."
            ></a-input>
          </a-form-item>
          <a-form-item
            label="序号"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <a-input
              v-decorator="[
                'serial_no',
                {rules: [{ required: true, message: '请输入序号!!' }]}
              ]"
              placeholder="请输入序号..."
            ></a-input>
          </a-form-item>
          <a-form-item
            label="类型"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <a-radio-group v-model="addressType">
              <a-radio :value="1">省</a-radio>
              <a-radio :value="2">市</a-radio>
              <a-radio :value="3">区</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>

      </div>
    </a-modal>
    <!--地址上下架-->
    <a-modal
      title="地址上下架"
      v-model="shelfVisible"
      @ok="changeState"
      okText="确认"
      cancelText="取消"
    >
      <a-radio-group v-model="upper_shelf_state">
        <a-radio :value="1">上架</a-radio>
        <a-radio :value="2">下架</a-radio>
      </a-radio-group>
    </a-modal>
  </div>
</template>

<script>
import { regionQuery, regionSave, regionById, regionDelete, upperShelfState } from '@/api/region'
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    slots: { title: 'type' },
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '状态',
    dataIndex: 'upper_shelf_state',
    key: 'upper_shelf_state',
    slots: { title: 'state' },
    scopedSlots: { customRender: 'state' }
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
  },
  onSelect: (record, selected, selectedRows) => {
    console.log(record, selected, selectedRows)
  },
  onSelectAll: (selected, selectedRows, changeRows) => {
    console.log(selected, selectedRows, changeRows)
  }
}
export default {
  name: 'AddressManagement',
  data () {
    return {
      province: false,
      upper_shelf_state: 1,
      id: 0,
      shelfVisible: false,
      isEdit: false,
      visible: false,
      addressTemp: {},
      dialogModel: this.$form.createForm(this),
      addressType: 1,
      confirmLoading: false,
      columns,
      rowSelection,
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0
      },
      cityData: [],
      replaceFields: {
        children: 'regions',
        title: 'name',
        key: 'id'
      },
      expandedKeys: ['0-0-0', '0-0-1'],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: []
    }
  },
  mounted () {
    this.getList()
  },
  watch: {
    checkedKeys (val) {
      console.log('onCheck', val)
    }
  },
  methods: {
    // 上下架
    changeShelves (address) {
      this.shelfVisible = true
      this.upper_shelf_state = address.upper_shelf_state
      this.id = address.id
    },

    changeState: function () {
      upperShelfState({
        id: this.id,
        upper_shelf_state: this.upper_shelf_state
      })
        .then(res => {
          console.log(res)
          this.shelfVisible = false
          if (res) { this.$message.success('上架操作成功！') }
          this.getList()
        })
        .catch(err => {
          console.log(err)
          this.shelfVisible = false
          this.$message.error('上架操作失败！')
        })
    },

    // 显示新增弹窗
    showAddressModal (data) {
      this.isEdit = false
      this.province = false
      this.visible = true
      this.addressTemp = data
    },

    // 关闭弹窗
    handleCancel () {
      this.visible = false
    },

    // 编辑
    showEditModal (data) {
      this.isEdit = true
      this.province = false

      console.log(data)
      this.addressTemp = data
      this.visible = true
      this.getAddressById(data.id).then(address => {
        // 赋值
        this.dialogModel.setFieldsValue({
          name: address.name,
          serial_no: address.serial_no
        })
        this.addressType = address.type
      })
    },

    // 根据id获取地址
    async getAddressById (id) {
      let result
      await regionById({ id })
        .then(res => {
          console.log(res)
          result = res
        })
        .catch(err => {
          console.log(err)
        })
      return result
    },

    addProvince () {
      this.province = true
      this.isEdit = false
      this.visible = true
    },

    // 保存
    saveAddress: function () {
      this.dialogModel.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          values.type = this.addressType

          if (!this.province) {
            values.father_id = !this.isEdit ? this.addressTemp.id : this.addressTemp.father_id
            values.type = this.addressType
            if (this.isEdit) { values.id = this.addressTemp.id }
          }

          regionSave(values)
            .then(res => {
              this.visible = false
              this.confirmLoading = false
              if (res) { this.$message.success('新增地址成功！') }
              this.getList()
            })
            .catch(err => {
              console.log(err)
              this.visible = false
              this.confirmLoading = false
              this.$message.error('新增地址失败！')
            })
        }
      })
    },

    // 删除
    delAddress (id) {
      regionDelete({ id })
        .then(res => {
          console.log(res)
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 获取列表
    getList: function () {
      const param = {
        page_index: this.pagination.pageNo,
        page_size: this.pagination.pageSize
      }
      regionQuery(param)
        .then(res => {
          console.log(res)
          this.cityData = res
        })
        .catch(err => {
          console.log(err)
        })
    },

    onExpand (expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck (checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect (selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
    }
  }
}
</script>

<style scoped>

</style>
